<template>
  <div class="p2">
    <el-dialog v-model="userStore.visiable" :title="userStore.title" :show-close="false" ref="dialog">
      <template #header>
        <div class="dialog-header">
          <span>{{ userStore.title }}</span>
        </div>
      </template>
      <template #default>
        <div class="dialog-default">
          <el-row>
            <el-col :span="12">
              <div class="left">
                <div class="phone" v-show="scene == 0">
                  <div class="top">
                    <el-form :model="loginParam" :rules="rules" ref="form">
                      <el-form-item prop="phone">
                        <el-input placeholder="请你输入手机号码" :prefix-icon="User" v-model="loginParam.phone"></el-input>
                      </el-form-item>
                      <el-form-item prop="code">
                        <el-input placeholder="请输入手机验证码" :prefix-icon="Lock" v-model="loginParam.code"></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button :disabled="!isPhone || flag ? true : false">
                          <Countdown v-if="flag" :flag="flag" @getFlag="getFlag"></Countdown>
                          <span v-else @click="getCode">获取验证码</span>
                        </el-button>
                      </el-form-item>
                    </el-form>
                    <el-button style="width: 100%" type="primary" size="default" :disabled="!isPhone || loginParam.code.length < 6 ? true : false" @click="login">用户登录</el-button>
                  </div>
                  <div class="bottom" @click="changeScene">
                    <p>微信扫码登录</p>
                    <svg-icon icon-class="wechat"></svg-icon>
                  </div>
                </div>
                <div class="wechat" v-show="scene == 1">
                  <div class="top">
                    <img src="@/assets/images/code_app.png" alt="" />
                  </div>
                  <div class="bottom" @click="handler">
                    <p>手机号码登录</p>
                    <svg-icon icon-class="phone"></svg-icon>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="right">
                <div class="item">
                  <div class="top">
                    <img src="@/assets/images/code_app.png" alt="" />
                  </div>
                  <div class="bottom">
                    <svg-icon icon-class="wechat"></svg-icon>
                    <span>微信扫一扫关注</span>
                    <span>APP</span>
                  </div>
                </div>
                <div class="item">
                  <div class="top">
                    <img src="@/assets/images/code_login_wechat.png" alt="" />
                  </div>
                  <div class="bottom">
                    <svg-icon icon-class="phone"></svg-icon>
                    <span>微信扫一扫下载</span>
                    <span>WeChat</span>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" size="default" @click="closeDialog">关闭窗口</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Login" setup lang="ts">
//引入wx扫码登录参数请求
import { reqWxLogin } from "@/api/Hospital";
import { ElMessage } from "element-plus";
//引入倒计时组件
import Countdown from "@/components/Countdown/index.vue";
import { ref, reactive, computed, watch } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import type { WXLoginResponseData } from "@/api/Hospital/types";
import { useRouter, useRoute } from 'vue-router';
//获取user仓库的数据( visiable)可以控制login组件的对话框显示与隐藏
import useUserStore from "@/store/modules/user";

let userStore = useUserStore();
//获取路由器对象
let $router = useRouter();
let $route = useRoute()

//定义一个响应式数据控制倒计时组件显示与隐藏
let flag = ref<boolean>(false); //flag如果为真,开启倒计时  flag:为假的并非倒计时
let scene = ref<number>(0); //0代表收集号码登录  如果是1 微信扫码登录
//获取form组件实例
let form = ref<any>();
//收集表单数据---手机号码
let loginParam = reactive({
  phone: "", //收集手机号码
  code: "", //收集验证码
});
//计算出当前表单元素收集的内容是否手机号码格式
let isPhone = computed(() => {
  //手机号码正则表达式
  const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
  //返回布尔值:真代表手机号码、假代表的即为不是手机号码
  return reg.test(loginParam.phone);
});
//点击微信扫码登录|微信小图标切换为微信扫码登录
const changeScene = async () => {
  //切换场景为1
  scene.value = 1;
  //发请求获取微信扫码二维码需要参数
  //咱们在想硅谷学校的服务器发请求,获取微信扫码登录页面参数
  //还需要携带一个参数:告诉学校服务器用户授权成功以后重定向项目某一个页面
  let redirect_URL = encodeURIComponent(window.location.origin + "/wxlogin");
  let result: WXLoginResponseData = await reqWxLogin(redirect_URL);
  //生成微信扫码登录二维码页面
  new WxLogin({
    self_redirect: true, //true:手机点击确认登录后可以在 iframe 内跳转到 redirect_uri
    id: "login_container", //显示二维码容器设置
    appid: result.data.appid, //应用位置标识appid
    scope: "snsapi_login", //当前微信扫码登录页面已经授权了
    redirect_uri: result.data.redirectUri, //填写授权回调域路径,就是用户授权成功以后，微信服务器向公司后台推送code地址
    state: result.data.state, //state就是学校服务器重定向的地址携带用户信息
    style: "black",
    href: "",
  });
};
//获取验证码按钮的回调
const getCode = async () => {
  //解决element-plus按钮禁用还能点击的问题
  if (!isPhone.value || flag.value) return;
  //开启倒计时模式,倒计时组件显示出来
  flag.value = true;
  //通知pinia仓库存储验证码
  try {
    //获取验证码成功
    await userStore.getCode(loginParam.phone);
    loginParam.code = userStore.code;
  } catch (error) {
    ElMessage({
      type: "error",
      message: (error as Error).message,
    });
  }
};

//计数器子组件绑定的自定义事件
//当倒计时为零的时候,通知父组件倒计时组件隐藏
const getFlag = (val: boolean) => {
  //倒计时模式结束
  flag.value = val;
};

//点击用户登录按钮回调
const login = async () => {
  //保证表单校验两项都复合条件
  await form.value.validate();
  //发起登录请求
  //登录请求成功:顶部组件需要展示用户名字、对话框关闭
  //登录请求失败:弹出对应登录失败的错误信息
  try {
    console.log(loginParam);
    //用户登录成功
    await userStore.userLogin(loginParam);
    //关闭对话框
    userStore.visiable = false;
    //获取url的query参数
    let redirect = $route.query.redirect;
    if (redirect) {
      $router.push(redirect as string);
    } else {
      $router.push('/home');
    }
  } catch (error) {
    ElMessage({
      type: "error",
      message: (error as Error).message,
    });
  }
};

//自定义校验规则:手机号码自定义校验规则
const validatorPhone = (rule: any, value: any, callBack: any) => {
  //rule:即为表单校验规则对象
  //value:即为当前文本的内容
  //callBack:回调函数
  const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
  if (reg.test(value)) {
    callBack();
  } else {
    callBack(new Error("请输入正确的手机号码格式"));
  }
};
//验证码自定义校验规则
const validatorCode = (rule: any, value: any, callBack: any) => {
  //rule:即为表单校验规则对象
  //value:即为当前文本的内容
  //callBack:回调函数
  if (/^\d{6}$/.test(value)) {
    callBack();
  } else {
    callBack(new Error("请输入正确的验证码格式"));
  }
};
//表单校验的规则对象
const rules = {
  //手机号码校验规则
  //required:代表当前字段务必进行校验
  //message:代表的校验错误的提示信息
  //trigger:代表表单校验触发的时机  change:文本发生变化的时候进行校验  blur:失却焦点的时候触发校验
  //min:代表的是最小位数
  //max:代表的是最大的位置
  // phone: [{ required: true, message: "手机号码务必11位", trigger: "change", min: 11 }],
  // code: [{ required: true, message: "验证码务必6位", trigger: "blur", min: 6 }],

  phone: [{ trigger: "change", validator: validatorPhone }],
  code: [{ trigger: "change", validator: validatorCode }],
};
//关闭窗口按钮的回调
const closeDialog = () => {
  userStore.visiable = false;
};

//点击手机短信验证码盒子回调
const handler = () => {
  scene.value = 0;
};

//监听场景的数据
watch(
  () => scene.value,
  (val: number) => {
    if (val === 1) {
      userStore.queryState();
    }
  }
);
</script>

<style scoped lang="scss">
.dialog-header {
  background-color: #f4f4f4;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 900;
}

.dialog-default {
  .left {
    width: 464px;
    height: 288px;

    .phone {
      color: #333333;
      padding: 20px;
      background-color: #f4f4f4;

      .top {
        width: 424px;
        height: 182px;
      }

      .bottom {
        width: 424px;
        height: 66px;
        display: flex;
        flex-direction: column;
        align-items: center;

        p {
          margin: 10px 0px;
        }
      }
    }

    .wechat {
      color: #333333;
      padding: 20px;
      background-color: #f4f4f4;

      .top {
        width: 424px;
        height: 182px;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          width: 182px;
        }
      }

      .bottom {
        width: 424px;
        height: 66px;
        display: flex;
        flex-direction: column;
        align-items: center;

        p {
          margin: 10px 0px;
        }
      }
    }
  }

  .right {
    width: 464px;
    height: 288px;
    display: flex;
    justify-content: space-around;
    background-color: #f4f4f4;

    .item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .top {
        height: 182px;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          width: 130px;
          height: 130px;
        }
      }

      .bottom {
        height: 66px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      span {
        margin: 5px 0;
      }
    }
  }
}

.dialog-footer {
  background-color: #f4f4f4;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
